import { useModel } from 'umi';
import React, { useRef, useEffect, useState } from 'react';
import {
  Row,
  Col,
  Tree,
  message,
  Card,
  Space,
  Button,
  Drawer,
  Checkbox,
  Tooltip,
  Spin,
} from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import ProForm, {
  ProFormText,
  ProFormSwitch,
  ProFormDigit,
  ProFormTreeSelect,
  ProFormSelect,
} from '@ant-design/pro-form';
import {
  add,
  del,
  update,
  menulist,
  actionclasslist,
  actionlist,
  editmenubindingaction,
  menubindingaction,
} from './service';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons';
import * as Icon from '@ant-design/icons';
import AuthorityButton from '@/components/AuthorityButton';
const Menu = () => {
  const { initialState } = useModel('@@initialState');
  const formActionRef = useRef();
  const formRef = useRef();
  const [currentMenu, SetCurrentMenu] = useState(undefined);
  const [state, setState] = useState('read');
  const [treeData, SetTreeData] = useState([]);
  const [cardTitle, SetCardTitle] = useState('详情');
  const [actionClassData, SetActionClassData] = useState([]);
  const [actionData, SetActionData] = useState([]);
  //drawer 显示控制
  const [drawerVisible, setDrawerVisible] = useState(false);

  //多选按钮样式
  const [indeterminate, setIndeterminate] = React.useState(false);
  const [checkAll, setCheckAll] = React.useState(false);
  const [checkedList, setCheckedList] = React.useState([]);
  const [actionClassList, setActionClassList] = React.useState([]);
  const [loading, setLoading] = React.useState(false);

  //初始化数据
  useEffect(() => {
    const initData = (value) => {
      var res = initialState?.currentUser?.menuList;
      if (res) {
        SetTreeData(res);
      }
      actionclasslist().then((re) => {
        if (re.isSuccess) {
          SetActionClassData(re.data);
        }
      });
    };
    initData();
  }, []);

  //获取菜单数据
  const getMenuList = async () => {
    await menulist().then((r) => {
      if (r.isSuccess) {
        SetTreeData(r.data);
      }
    });
  };
  const onSelect = (keys, info) => {
    setState('read');
    SetCurrentMenu(info.node.info);
    formRef?.current?.setFieldsValue(info.node.info);
  };

  const onExpand = () => {
    console.log('Trigger Expand');
  };

  //获取Actionlist
  const getActionlist = async (value) => {
    await actionlist(value).then((re) => {
      if (re.isSuccess) {
        var list = [];
        re?.data.map((item) => {
          list.push({ label: item.name, value: item.id });
        });
        SetActionData(list);
        var cl = new Set(checkedList);
        // 交集
        setCheckedList(list.map((x) => x.value).filter((x) => cl.has(x)));
      }
    });
  };
  const onCheckAllChange = (e) => {
    setCheckedList(e.target.checked ? actionData?.map((item) => item.value) : []);
    setIndeterminate(false);
    setCheckAll(e.target.checked);
  };
  const onCheckChange = (list) => {
    setCheckedList(list);
    setIndeterminate(!!list.length && list.length < actionData.length);
    setCheckAll(list.length === actionData.length);
  };

  //
  const loopMenuItem = (menus) =>
    menus?.map((item, index) => {
      if (typeof item.icon != 'undefined' && Icon[item.icon] != undefined) {
        return {
          key: item.id,
          title: item.name,
          icon: item.icon && React.createElement(Icon[item.icon]),
          routes: item.routes && loopMenuItem(item.routes),
          children: item.routes && loopMenuItem(item.routes),
          value: item.id,
          info: item,
          hideInMenu: item.hideInMenu,
          label: item.name,
        };
      } else {
        return {
          key: item.id,
          title: item.name,
          value: item.id,
          routes: item.routes && loopMenuItem(item.routes),
          children: item.routes && loopMenuItem(item.routes),
          info: item,
          hideInMenu: item.hideInMenu,
          label: item.name,
        };
      }
    });

  return (
    <PageContainer>
      <Row gutter={16}>
        <Col span={18} push={6}>
          <Card
            title={cardTitle}
            extra={
              <Space>
                <Button
                  style={{ display: currentMenu ? 'block' : 'none' }}
                  type="primary"
                  onClick={() => {
                    setState('edit');
                    SetCardTitle('修改');
                  }}
                >
                  修改
                </Button>
                <Button
                  onClick={() => {
                    setState('edit');
                    SetCurrentMenu(undefined);
                    formRef.current.resetFields(undefined);
                    SetCardTitle('新增');
                  }}
                >
                  新增
                </Button>
              </Space>
            }
          >
            <ProForm
              formRef={formRef}
              labelCol={{ span: 8 }}
              wrapperCol={{ span: 16 }}
              layout={'horizontal'}
              submitter={
                state == 'read'
                  ? false
                  : {
                    render: (props, doms) => {
                      return (
                        <Row>
                          <Col span={16} offset={8}>
                            <Space>{doms}</Space>
                          </Col>
                        </Row>
                      );
                    },
                  }
              }
              onFinish={async (values) => {
                var res = { isSuccess: false };
                res = currentMenu ? await update(values) : await add(values);
                if (res.isSuccess) {
                  getMenuList();
                  currentMenu ? SetCurrentMenu(values) : SetCurrentMenu(res.data);
                  setState('read');
                  SetCardTitle('详情');
                  message.success(res.msg);
                } else {
                  message.error(res.msg);
                }
              }}
            >
              <ProFormText name="id" hidden />
              <ProFormText
                mode={state}
                name="name"
                width="md"
                label="菜单名称"
                placeholder="菜单名称"
              />
              <ProFormTreeSelect
                mode={state}
                name="parentId"
                width="md"
                label="父级菜单"
                placeholder="父级菜单"
                request={() => {
                  var data = [{ key: 0, title: '顶层', value: 0, label: '顶层' }];
                  return [...data, ...loopMenuItem(treeData)];
                }}
              />
              <ProFormText
                mode={state}
                name="path"
                width="md"
                label="菜单路径"
                placeholder="路径"
              />
              <ProFormText
                mode={state}
                name="component"
                width="md"
                label="全路径"
                placeholder="全路径"
              />
              <ProFormTreeSelect
                mode={state}
                name="parentId"
                width="md"
                label="父级菜单"
                placeholder="父级菜单"
                request={() => {
                  var data = [{ key: 0, title: '顶层', value: 0, label: '顶层' }];
                  return [...data, ...loopMenuItem(treeData)];
                }}
              />
              <ProFormText mode={state} name="access" width="md" label="权限" placeholder="权限" />
              <ProFormText
                mode={state}
                name="icon"
                width="md"
                label="图标"
                placeholder="图标"
                request={() => {
                  var list = [];
                  [...new Set(Object.keys(Icon))]?.map((item, index) => {
                    list.push({ label: item && React.createElement(Icon[item]), value: item });
                  });
                  return list;
                }}
              />
              <ProFormSwitch mode={state} name="hideInMenu" label="是否隐藏" />
              <ProFormDigit mode={state} label="排序" name="sort" width="sm" />
            </ProForm>
          </Card>
        </Col>
        <Col span={6} pull={18}>
          <Tree
            showIcon
            height={600}
            onSelect={onSelect}
            onExpand={onExpand}
            treeData={loopMenuItem(treeData)}
            key="id"
            titleRender={(nodeData) => {
              return (
                <Space size={'large'}>
                  {nodeData.label}
                  <Space style={{ float: 'right' }}>
                    <AuthorityButton
                      type={'link'}
                      key="update"
                      class={'update'}
                      text={
                        <Tooltip placement="topLeft" title="修改后台功能模块">
                          <EditOutlined />
                        </Tooltip>
                      }
                      onClick={async () => {
                        setCheckedList([]);
                        setActionClassList([]);
                        formActionRef.current?.resetFields(undefined);
                        setLoading(true);
                        setDrawerVisible(true);
                        await menubindingaction(nodeData.key).then(async (re) => {
                          if (re.isSuccess) {
                            await getActionlist(re.data.actionClassList);
                            setActionClassList(re.data.actionClassList);
                            setCheckedList(re.data.actionIds);
                          }
                        });
                        setLoading(false);
                      }}
                    />
                    <AuthorityButton
                      type={'popconfirm'}
                      key="del"
                      class={'delete'}
                      text={
                        <Tooltip placement="topLeft" title="删除">
                          <DeleteOutlined />
                        </Tooltip>
                      }
                      onConfirm={() => {
                        del([nodeData.key]).then((re) => {
                          if (re.isSuccess) {
                            getMenuList();
                            message.success(re.msg);
                          } else {
                            message.error(re.msg);
                          }
                        });
                      }}
                    />
                  </Space>
                </Space>
              );
            }}
          />
          <Drawer
            title="后台功能模块"
            placement="right"
            size="large"
            onClose={() => {
              setDrawerVisible(false);
            }}
            visible={drawerVisible}
            extra={
              <Space>
                <Button
                  onClick={() => {
                    setCheckedList([]);
                    setActionClassList([]);
                    formActionRef.current?.resetFields(undefined);
                  }}
                >
                  重置
                </Button>
                <Button
                  type="primary"
                  onClick={() => {
                    formActionRef.current?.submit();
                  }}
                >
                  提交
                </Button>
              </Space>
            }
          >
            <Spin spinning={loading}>
              <ProForm
                formRef={formActionRef}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                layout={'horizontal'}
                submitter={{
                  render: (props, doms) => {
                    return false;
                  },
                }}
                onFinish={async (values) => {
                  var res = { isSuccess: false };
                  res = await editmenubindingaction({
                    menuId: currentMenu.id,
                    actionIds: checkedList,
                  });
                  if (res.isSuccess) {
                    setDrawerVisible(false);
                    message.success(res.msg);
                  } else {
                    message.error(res.msg);
                  }
                }}
              >
                <ProFormSelect
                  fieldProps={{
                    mode: 'multiple',
                  }}
                  label="后台模块"
                  name="actionClassList"
                  placeholder="后台模块"
                  value={actionClassList}
                  onChange={async (values) => {
                    await getActionlist(values);
                  }}
                  request={() => {
                    var list = [];
                    [...new Set(actionClassData)]?.map((item, index) => {
                      list.push({ label: item, value: item });
                    });
                    return list;
                  }}
                />

                <ProForm.Item name="checkedList" label="功能项">
                  <Checkbox
                    indeterminate={indeterminate}
                    onChange={onCheckAllChange}
                    hecked={checkAll}
                  >
                    全选
                  </Checkbox>
                  <br />
                  <Checkbox.Group
                    options={actionData}
                    value={checkedList}
                    onChange={onCheckChange}
                  />
                </ProForm.Item>
              </ProForm>
            </Spin>
          </Drawer>
        </Col>
      </Row>
      ,
    </PageContainer>
  );
};

export default Menu;
